package com.qc.common.base;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * Service基类
 */
@Transactional(readOnly = true)
public abstract class BaseService<D extends BaseDao<T>, T extends BaseEntity> {
    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 持久层对象
     */
    @Autowired
    protected D basedao;

    /**
     * 获取单条数据
     *
     * @param id
     * @return
     */
    public T get(String id) {
        return basedao.get(id);
    }

    /**
     * 获取单条数据
     *
     * @param entity
     * @return
     */
    public T get(T entity) {
        return basedao.get(entity);
    }

    /**
     * 查询列表数据
     *
     * @param entity
     * @return
     */
    public List<T> findList(T entity) {
        return basedao.findList(entity);
    }

    /**
     * 查询分页数据
     *
     * @param object
     * @return
     */
    public List<T> findListPage(T object) {
        if (object.getPage() != null && object.getLimit() != null) {
            PageHelper.startPage(object.getPage(), object.getLimit());
        }
        return this.basedao.findList(object);
    }

    /**
     * 保存数据（插入或更新）
     *
     * @param entity
     */
    @Transactional(readOnly = false)
    public void save(T entity) {
        if(StringUtils.isBlank(entity.getId())) {
            entity.preInsert();
            try {
                this.basedao.insert(entity);
            }catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("保存失败", e);
            }
        }else {
            entity.preUpdate();
            try {
                this.basedao.update(entity);
            }catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("更新失败", e);
            }
        }
    }

    /**
     * 删除数据
     *
     * @param entity
     */
    @Transactional(readOnly = false)
    public void delete(T entity) {
        basedao.delete(entity.id);
    }

}